<?php

/**
 * 积分兑换记录
 * File Name：RedeemRecordsModel.php
 * File Encoding：UTF-8
 * File New Time：2014-6-14 9:40:58
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class RedeemRecordsModel extends BaseModel {

    CONST SURE_NOT = 0; //未确定
    CONST SURE_HAS = 1; //已确定
    CONST SURE_ING = 2; //确定中
    CONST SURE_CANCEL = 3; //已取消
    //NODE
    //CONST REFUND_NOT = 0; //未退款
    //CONST REFUND_HAS = 1; //已退款
    CONST REFUND_NOT = 0; //未发货
    CONST REFUND_HAS = 1; //已发货

    public function tableName() {
        return '{{redeem_records}}';
    }

    public function rules() {
        return array(
            array('uid', 'required', 'message' => '用户UID不能为空！'),
            array('username', 'required', 'message' => '用户名不能为空！'),
            array('redeem_id', 'required', 'message' => '所属对话积分商品ID不能为空！'),
            array('integral', 'required', 'message' => '兑换积分数不能为空！'),
            array('order_sn', 'match', 'pattern'=>'/^[ A-Za-z0-9]+$/u','message'=>'订单不合法！'),            
            //无需检查
            array('record_time,ip,is_refund,is_sure,order_submit_time,seller_uid,remarks', 'safe'),
        );
    }

    public function relations() {
        return array(
            'RedeemModel' => array(self::BELONGS_TO, 'RedeemModel', 'redeem_id'),
            'MembersModel' => array(self::BELONGS_TO, 'MembersModel', 'uid'),

            'MembersModel_seller' => array(self::BELONGS_TO, 'MembersModel', 'seller_uid'),
            'MembersInfoModel_seller' => array(self::BELONGS_TO, 'MembersModel', 'seller_uid'),
        );
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    //获取当前兑换商品，已经兑换次数
    public function getRedeemSum($redeem_id) {
        if (empty($redeem_id)) {
            return 0;
        }
        $arrData = array(
            'condition' => 'redeem_id = :redeem_id AND is_sure != :is_sure',
            'params' => array('redeem_id' => $redeem_id, 'is_sure' => self::SURE_CANCEL),
        );
        return $this->count($arrData);
        //return $this->count($this->where(array('redeem_id' => $redeem_id, 'is_sure' => array('NT', self::SURE_CANCEL))));
    }

    //该兑换商品，用户已经兑换多少次了
    public function getUserRedeemSum($uid, $redeem_id) {
        if (empty($uid) || empty($redeem_id)) {
            return 0;
        }
        $arrData = array(
            'condition' => 'redeem_id = :redeem_id AND is_sure != :is_sure AND uid = :uid',
            'params' => array('redeem_id' => $redeem_id, 'is_sure' => self::SURE_CANCEL, 'uid' => $uid),
        );
        return $this->count($arrData);
        //return $this->count($this->where(array('uid' => $uid, 'redeem_id' => $redeem_id, 'is_sure' => array('!=', self::SURE_CANCEL))));
    }

    //添加兑换记录
    public function addLogs($redeemObject, $userInfo = '') {
        empty($userInfo) ? $userInfo = Yii::app()->user->getInfo() : '';
        if (!is_object($redeemObject)) {
            return false;
        }
        $this->uid = $userInfo['uid'];
        $this->username = $userInfo['username'];
        $this->redeem_id = $redeemObject->id;
        $this->integral = $redeemObject->integral;
        $this->is_refund = self::REFUND_NOT;
        $this->is_sure = self::SURE_NOT;
        $this->seller_uid = $redeemObject->uid;
        $this->setIsNewRecord(true);
        if ($this->validate() && $this->save()) {
            return true;
        }
        return false;
    }

    public function attributeLabels() {
        return array(
            'username' => '用户名',
            'integral' => '兑换积分',
            'record_time' => '兑换时间',
            'order_sn' => '订单号',
            'record_time' => '兑换时间',
            'is_refund' => '是否返款',
            'is_sure' => '商家是否确定',
            'order_submit_time' => '提交订单时间',
            'seller_uid' => '卖家ID',
        );
    }

    //数据保存前操作
    protected function beforeSave() {
        //是否新增
        if ($this->isNewRecord) {
            //添加时间
            $this->record_time = time();
            $this->ip = GuestDataModel::model()->getForwardedForIp();
        } else {
            
        }
        return true;
    }

    public static function getRefundHtmlList() {
        //NODE
        return array(
            self::REFUND_NOT => '未发货',
            self::REFUND_HAS => '已发货',
        );
    }

    public static function getRefundHtmlDetail($refund) {
        $arrData = self::getRefundHtmlList();
        return $arrData[$refund];
    }

    public static function getSureHtmlList() {
        return array(
            self::SURE_NOT => '未确定',
            self::SURE_HAS => '已确定',
            self::SURE_ING => '确定中',
            self::SURE_CANCEL => '已取消',
        );
    }

    public static function getSureHtmlDetail($sure) {
        $arrData = self::getSureHtmlList();
        return $arrData[$sure];
    }

    public function createSearchCriteria() {
        $criteria = new CDbCriteria();

        $criteria->compare('t.uid', $this->uid);
        $criteria->compare('t.username', $this->username, true);
        $criteria->compare('t.ip', $this->ip);
        $criteria->compare('t.order_sn', $this->order_sn, true);
        $criteria->compare('t.redeem_id', $this->redeem_id);
        $criteria->compare('t.is_sure', $this->is_sure);
        $criteria->compare('t.is_refund', $this->is_refund);

        if (isset($_GET['is_order_sn'])) {
            switch ($_GET['is_order_sn']) {
                case 2:
                    $criteria->addCondition('order_sn = "" || order_sn = null');
                    break;
                case 1:
                    $criteria->addCondition('order_sn != ""');
                    break;
            }
        }

        if (!empty($_GET['start_time'])) {
            $start_time = strtotime($_GET['start_time']);
            $criteria->addCondition("record_time >= $start_time ");
        }

        if (!empty($_GET['end_time'])) {
            $end_time = strtotime($_GET['end_time']) + 86399;
            $criteria->addCondition("record_time <= $end_time ");
        }


        return $criteria;
    }

    /**
     * 判断用户是否可以修改订单号
     * @return [type] [description]
     */
    public function canEditOrder($uid = '') {
        empty($uid) ? $uid = Yii::app()->user->uid : '';

        //检查地址是否有填写
        $arrResult = array();
        $userAddres = MembersAddressModel::model()->getMemberAddres($uid);
        if (empty($userAddres->address) || empty($userAddres->consignee)) {
            $arrResult[] = 'address';
        }
        //旺旺，支付宝
        $memberTaobao = MembersTaobaoModel::model()->getMemberTB($uid);
        if (empty($memberTaobao->taobao_user_nick)) {
            $arrResult[] = 'wanwan';
        }
        $memberInfo = MembersModel::model()->findByPk($uid);
        if (empty($memberInfo->alipay)) {
            $arrResult[] = 'alipay';
        }

        if ($arrResult) {
            return $arrResult;
        }
        //7天的时间没有提交订单自动放弃这兑换
        /*        if(!$this->order_submit_time && time() - $this->record_time > 7 * 24 * 3600)
          {
          $this->addError('', '已过期');
          return false;
          } */


        if ($this->is_sure == self::SURE_NOT) {
            //当提交过如果超过三天我们改为自动已经确定
            /*            if($this->order_submit_time)
              {
              if(time() - $this->order_submit_time >= 3 * 3600 * 24)
              {
              $this->is_sure = self::SURE_AUTO;
              $this->save(ture, array('is_sure'));
              $this->addError('', '已经自动确定');
              return false;
              }
              } */
            return true;
        }
        $this->addError('', '已经确定');
        return false;
    }
    /**
     * 晒积分记录的单
     * @return [type] [description]
     */
    public function post($experience, $userInfo = ''){
        if(!is_array($userInfo) && !empty($userInfo)){
            $userInfo = MembersModel::model()->getUserInfo($userInfo);
        }
        empty($userInfo) ? $userInfo = yii::app()->user->getInfo() : '';
        $objRedeemModel = $this->RedeemModel;
        $subject = "{$objRedeemModel->title}";
        $url = Yii::app()->request->hostInfo.yii::app()->createUrl('/front/index/score');
        $url = "[url=$url]我也要买[/url]";
        $message = "[size=3][b]产品名称[/b]：{$objRedeemModel->title}\n[b]所需积分[/b]：{$objRedeemModel->integral}\n[img=100,100]{$objRedeemModel->thumb}[/img]\n$url\n[b]价格[/b]：[color=Red][b][i]{$objRedeemModel->worth}元[/i][/b][/color]\n[b]购买心得[/b]:{$experience}[/size]";            
        $fid = 55;
        $typeid = 3;//主题类别 积分晒单或其它晒单
        $arrData = array(
            'subject' => $subject,
            'message' => $message,
            'fid' => $fid,
            'typeid' => $typeid,                        
        );
        //print_r($arrData);exit;
        //晒单后送积分
        yii::import('ext.yzwAPI.*');
        if(DzAPI::getInstance($userInfo)->post($arrData)){
            if(MembersModel::model()->plusScore($userInfo['uid'], 15)){
                MembersActionModel::model()->addShareAction($userInfo['uid'], '积分商品晒单送积分15个');
            }
            //标记为已晒
            $this->is_experience = 1;
            $this->save(false,array('is_experience'));        
            return true;
        }else{
            return false;
        }
    }
}
